package com.amar.dtadmin.apidoc.ui.dialog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.amar.dtadmin.apidoc.extensions.storages.DtAdminSettings;
import com.amar.dtadmin.apidoc.fegin.DtAdminClient;
import com.amar.dtadmin.apidoc.model.DtAdminLoginResp;
import com.amar.dtadmin.apidoc.model.DtAdminUserInfoResp;
import com.amar.dtadmin.apidoc.model.Response;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.ValidationInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xiaoshiqiang
 * @since 2025/2/9
 */
public class DtAdminSettingsDialog extends DialogWrapper {
    private final DtAdminSettings dtAdminSettings;
    private final DtAdminSettingsForm form;
    private final Project project;
    private final List<ValidationInfo> validationInfos = new ArrayList<>();

    public DtAdminSettingsDialog(Project project) {
        super(true); // true = 模态对话框
        this.project = project;
        form = new DtAdminSettingsForm();
        dtAdminSettings = DtAdminSettings.getInstance(project);
        form.fillForm(dtAdminSettings);

        init(); // 必须调用，加载 UI
        setTitle("DtAdmin平台配置");
        setSize(600, 200);
    }

    @Override
    protected @Nullable JComponent createCenterPanel() {
        return form.getContentPanel();
    }

    @Override
    protected @NotNull List<ValidationInfo> doValidateAll() {
        Map<JComponent, ValidationInfo> validationInfoMap = this.validationInfos.stream()
                .collect(Collectors.toMap(i -> i.component, Function.identity(), (k1, k2) -> k2, LinkedHashMap::new));
        ValidationInfo validateUsername = new ValidationInfo("用户名不能为空", form.getUsername()).withOKEnabled();
        ValidationInfo validatePassword = new ValidationInfo("密码不能为空", form.getPassword()).withOKEnabled();
        ValidationInfo validateProject = new ValidationInfo("项目编号不能为空", form.getProjectId()).withOKEnabled();

        validationInfoMap.remove(validateUsername.component, validateUsername);
        validationInfoMap.remove(validatePassword.component, validatePassword);
        validationInfoMap.remove(validateProject.component, validateProject);

        if (StrUtil.isEmpty(form.getUsername().getText())) {
            validationInfoMap.put(validateUsername.component, validateUsername);
        }
        if (StrUtil.isEmpty(new String(form.getPassword().getPassword()))) {
            validationInfoMap.put(validatePassword.component, validatePassword);
        }
        if (StrUtil.isEmpty(form.getProjectId().getText())) {
            validationInfoMap.put(validateProject.component, validateProject);
        }

        this.validationInfos.clear();
        this.validationInfos.addAll(validationInfoMap.values());
        return new ArrayList<>(validationInfoMap.values());
    }

    @Override
    protected void doOKAction() {
        DtAdminSettings settings = form.getFormData();
        DtAdminClient client = new DtAdminClient(project);
        List<ValidationInfo> validationInfos = new ArrayList<>();
        if (StrUtil.isNotEmpty(form.getToken().getText())) {
            Response<DtAdminUserInfoResp> response = client.userInfo(settings.getToken());
            if (response != null && response.getData() != null) {
                settings.setUsername(response.getData().getUserid());
                settings.setFullName(response.getData().getFullName());
            } else {
                validationInfos.add(new ValidationInfo("token无效", form.getToken()).withOKEnabled());
                updateErrorInfo(validationInfos);
                form.getToken().requestFocus();
            }
        } else {
            if (StrUtil.isNotEmpty(form.getUsername().getText()) && StrUtil.isNotEmpty(new String(form.getPassword().getPassword()))) {
                DtAdminLoginResp login = client.login(form.getUsername().getText(), new String(form.getPassword().getPassword()));
                if (login == null) {
                    validationInfos.add(new ValidationInfo("用户名或密码错误", form.getUsername()).withOKEnabled());
                    validationInfos.add(new ValidationInfo("用户名或密码错误", form.getPassword()).withOKEnabled());
                    updateErrorInfo(validationInfos);
                    form.getUsername().requestFocus();
                } else {
                    settings.setToken(login.getMessage().getAccessToken());
                    settings.setFullName(client.userInfo(login.getMessage().getAccessToken()).getData().getFullName());
                }
            }
        }

        if (CollUtil.isEmpty(this.validationInfos) && CollUtil.isEmpty(validationInfos)) {
            form.fillForm(settings);
            dtAdminSettings.loadState(settings);
            super.doOKAction();
        } else {
            this.validationInfos.clear();
            this.validationInfos.addAll(validationInfos);
        }
    }
}
